<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="注意：只能为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
            <el-row class="cat_option">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader v-model="cascaderVal"
                        :options="cateList"
                        :props="cascaderProps"
                        @change="cascaderChange"
                        clearable
                    ></el-cascader>
                </el-col>
            </el-row>
            <!--tab标签区-->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <!--动态参数面板-->
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="dialogAddVisible = true">添加参数</el-button>
                    <el-table :data="paramsData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-Tag v-for="(item,i) in scope.row.attr_vals" :key="'vals'+i" closable @close="deleteTag(i,scope.row)">{{item}}</el-Tag>
                                <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="dialogEditShow(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <!--静态属性面板-->
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="dialogAddVisible =true">添加属性</el-button>
                    <el-table :data="attrsData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-Tag v-for="(item,i) in scope.row.attr_vals" :key="'vals'+i" closable @close="deleteTag(i,scope.row)">{{item}}</el-Tag>
                                <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="dialogEditShow(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--添加动态参数/静态属性的弹框-->
        <el-dialog :title="'添加'+titleText" :visible.sync="dialogAddVisible" @close="dialogAddClose" width="500px">
            <el-form :model="newParams" :rules="newParamsRules" ref="newParamsRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="newParams.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="'编辑'+titleText" :visible.sync="dialogEditVisible" @close="dialogEditClose" width="500px">
            <el-form :model="editParams" :rules="newParamsRules" ref="editParamsRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editParams.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleEdit()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            cateList: [],
            cascaderProps: {
                expandTrigger: 'hover',
                label: 'cat_name',
                value: 'cat_id'
            },
            cascaderVal: [],
            activeName: 'many', // 被激活的标签页名称
            paramsData: [],
            attrsData: [],
            newParams: {
                'attr_name': ''
            },
            editParams: {},
            newParamsRules: {
                'attr_name': [
                    { required: true, message: '请输入参数名称', trigger: 'blur' }
                ]
            },
            dialogAddVisible: false,
            dialogEditVisible: false
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        async getCateList() {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.cateList = res.data
        },
        cascaderChange() {
            this.getParamsData()
        },
        handleTabClick() {
            this.getParamsData()
        },
        async getParamsData() {
            if (this.cascaderVal.length !== 3) { // 如果选中的不是三级分类
                this.cascaderVal = []
                this.paramsData = []
                this.attrsData = []
                return
            }
            const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, { params: { sel: this.activeName } })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
                // 控制文本框的显示与隐藏
                item.inputVisible = false
                // 文本框中输入的值
                item.inputValue = ''
            })
            if (this.activeName === "many") {
                // 如果是动态参数
                this.paramsData = res.data
            } else { // 如果是静态属性
                this.attrsData = res.data
            }
        },
        dialogAddClose() {
            this.$refs.newParamsRef.resetFields()
        },
        dialogEditClose() {
            this.$refs.editParamsRef.resetFields()
        },
        addParams() {
            // 添加参数分类
            this.$refs.newParamsRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post(`categories/${this.catId}/attributes`,
                {
                    attr_name: this.newParams.attr_name,
                    attr_sel: this.activeName
                    // attr_vals:''
                })
                if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                this.$message.success(res.meta.msg)
                this.getParamsData()
                this.dialogAddVisible = false
            })
        },
        async dialogEditShow(attrId) {
             // 打开并查询参数想去
            const { data: res } = await this.$http.get(`categories/${this.catId}/attributes/${attrId}`, { params: {
                attr_sel: this.activeName
            } })
            if (res.meta.status !== 200) {
                return this.$message.error(res.meta.msg)
            }
            this.editParams = res.data
            this.dialogEditVisible = true
        },
        handleDelete(attrId) {
            // 删除用户
            this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    const { data: res } = await this.$http.delete(`categories/${this.catId}/attributes/${attrId}`)
                    if (res.meta.status !== 200) {
                        return this.$message.error(res.meta.msg)
                    }
                    this.$message.success(res.meta.msg)
                    this.getParamsData()
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
        },
        handleEdit() {
            this.$refs.editParamsRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put(`categories/${this.catId}/attributes/${this.editParams.attr_id}`, {
                    attr_name: this.editParams.attr_name,
                    attr_sel: this.activeName
                })
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.dialogEditVisible = false
                this.getParamsData()
            })
        },
        showInput(row) {
            row.inputVisible = true
            // 让文本框自动获得焦点
            // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },
        // 将对 attr_vals 的操作，保存到数据库
        async saveAttrVals(row) {
            // 需要发起请求，保存这次操作
            const { data: res } = await this.$http.put(
                `categories/${this.catId}/attributes/${row.attr_id}`,
                {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(',') // 接收字符串，因此把数组拼接成用,分隔的字符串
                }
            )
            if (res.meta.status !== 200) {
                return this.$message.error('修改参数项失败！')
            }
            this.$message.success(res.meta.msg)
        },
        handleInputConfirm(row) {
            if (row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            let inputValue = row.inputValue.trim()
            if (inputValue) {
                row.attr_vals.push(inputValue)
            }
            row.inputVisible = false
            row.inputValue = ''
            this.saveAttrVals(row)
        },
        deleteTag(i, row) {
            row.attr_vals.splice(i, 1)
            this.saveAttrVals(row)
        }

    },
    computed: {
        isBtnDisabled() { // 按钮需要被禁用返回true
            if (this.cascaderVal.length !== 3) {
                return true
            }
            return false
        },
        catId() {
            if (this.cascaderVal.length === 3) {
                return this.cascaderVal[2]
            }
            return null
        },
        titleText() {
            if (this.activeName === "many") {
                return "动态参数"
            } else {
                return "静态属性"
            }
        }

    }
}
</script>

<style lang="less" scoped>
.cat_option{
    margin: 15px 0;
}
.el-tag{
    margin: 10px;
}
.input-new-tag{
    width: 150px;
}
</style>